import React, { useState, forwardRef, useImperativeHandle, useRef } from 'react';
import { Button, Select, Space } from 'antd';
import dayjs from 'dayjs';
import { reviewStatus, env } from '@/utils/data';
import Icon from '@/components/layout/Icon';
import MyModal from '@/components/modal';
import RelationTable from '../relationTable';
import styles from './index.module.css';

// record =>>>>>>>
// {
//   "project_id": 282,
//   "namespace": "easyhome-fe",
//   "project_name": "easyhome-workflow-manage",
//   "branch": "develop_code_20230425",
//   "review_status": 0 | 1 | 2,
//   "commit": {
//       "id": "c5d892b87a3a37c4e8ec6226a263b17e9c6c34fe",
//       "short_id": "c5d892b8",
//       "created_at": "2023-05-23T23:33:54.000+08:00",
//       "parent_ids": null,
//       "title": "feat：功能",
//       "message": "feat：功能",
//       "author_name": "赵美阳",
//       "author_email": "test@qq.com",
//       "authored_date": "2023-05-23T23:33:54.000+08:00",
//       "committer_name": "赵美阳",
//       "committer_email": "test@qq.com",
//       "committed_date": "2023-05-23T23:33:54.000+08:00",
//       "trailers": null,
//       "web_url": "http://gitlab.jrdaimao.com/easyhome-fe/easyhome-workflow-manage/-/commit/c5d892b87a3a37c4e8ec6226a263b17e9c6c34fe"
//   },
// }
// <<<<<<= record

// 表格列
const columns: any = (handlerOperation, checkLoading, developEnv) => [
  {
    title: '项目名称',
    dataIndex: 'project_name',
    width: '230px',
    fixed: 'left',
    render: (text: string, record: any) => (
      <a href={record.http_url_to_repo} target="_blank">
        {text}
      </a>
    ),
  },
  {
    title: '项目分支',
    dataIndex: 'branch',
    width: '200px',
    render: (text: string, record: { http_url_to_repo: string; branch: string }) => (
      <a href={`${(record.http_url_to_repo || '').replace('.git', '')}/-/tree/${record.branch}`} target="_blank">
        {text}
      </a>
    ),
  },
  {
    title: 'Review状态',
    dataIndex: 'review_status',
    width: '140px',
    align: 'center',
    render(text: number, record, index) {
      return (
        <Select
          suffixIcon={<Icon src="/images/arrow-down-solid-white.png" width={16} height={16} />}
          className={`code-selector code-select-bg${text}`}
          style={{ width: '100px', textAlign: 'left' }}
          options={reviewStatus}
          placeholder="review状态"
          value={text}
          onChange={(e) => {
            handlerOperation('status', record, index, e);
          }}
        ></Select>
      );
    },
  },
  {
    title: '开发环境',
    dataIndex: 'env',
    width: '230px',
    align: 'center',
    render(text, record, index) {
      let arr: any = [];
      if (Array.isArray(record.envList)) {
        arr = record.envList.map((item) => ({ label: item, value: item }));
      } else if (Array.isArray(developEnv)) {
        arr = developEnv;
      }
      if (arr && arr.length) {
        return (
          <Select
            onChange={(e) => {
              handlerOperation('env', record, index, e);
            }}
            style={{ width: '180px' }}
            placeholder="请选择开发环境"
            value={text}
            options={arr}
            mode="multiple"
          />
        );
      }
      if (text) {
        return text.toString();
      }
      return '-';
    },
  },
  {
    title: '开发人',
    dataIndex: 'developer',
    width: '120px',
    render(text) {
      if (!text || text.length <= 0) return <span>-</span>;
      if (Array.isArray(text)) {
        return <span>{text.join('，')}</span>;
      }
      return <span>{text}</span>;
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '180px',
    fixed: 'right',
    className: 'table-operation',
    render(text, record, index) {
      return (
        <Space wrap>
          <Button
            className="btn-link"
            type="link"
            onClick={() => {
              handlerOperation('diff', record);
            }}
          >
            diff分支地址
          </Button>
          <Button
            className="btn-link"
            type="link"
            onClick={() => {
              handlerOperation('record', record);
            }}
          >
            提交记录
          </Button>
          <Button
            className="btn-link"
            disabled={checkLoading}
            type="link"
            onClick={() => {
              handlerOperation('check', record);
            }}
          >
            代码质量检查
          </Button>
          <Button
            className="btn-link"
            type="link"
            onClick={() => {
              handlerOperation('delete', record, index);
            }}
          >
            取消关联
          </Button>
        </Space>
      );
    },
  },
];

const RelationProject = (props, ref) => {
  const { onOkCallback } = props;
  const [listDialog, setListDialog] = useState(false); // 需求关联项目弹框
  const relationTable = useRef<any>(null);
  const [relationTitile, setRelationTitle] = useState<string>(''); // 需求关联项目弹框title
  const tapd = useRef<any>(null); // 当前某个需求

  useImperativeHandle(ref, () => ({
    handleOpen(record) {
      // 接收过来的数据
      tapd.current = record;
      // 修改弹框标题
      setRelationTitle(record.name);
      // 打开弹框
      setListDialog(true);
    },
  }));

  // 添加项目按钮
  const handleAddProject = () => {
    relationTable.current.handleOpen();
  };

  return (
    <div className="relation-dialog">
      <MyModal
        destroyOnClose
        title="关联项目"
        open={listDialog}
        width={1200}
        onCancel={() => {
          setListDialog(false);
        }}
        onOk={() => {
          setListDialog(false);
        }}
      >
        <div>
          <div className={styles['story-title-box']}>
            <div>需求名称：{relationTitile}</div>
            <Button className="flex" onClick={handleAddProject} style={{ padding: '4px 8px' }} icon={<Icon src="/images/add-blue.png" width={16} height={16} style={{ marginRight: '4px' }} />}>
              添加项目
            </Button>
          </div>
          <RelationTable onOkCallback={onOkCallback} myRecord={tapd.current} columns={columns} ref={relationTable} />
        </div>
      </MyModal>
    </div>
  );
};

export default forwardRef(RelationProject);
